<template>
  <van-nav-bar
  title="创建订单"
  left-text="返回"
  left-arrow
  @click-left="onClickLeft"
/>
    <div class="add p-[20px]">
       
        <van-form @submit="onSubmit">
            <van-cell-group >
              <van-field
                v-model="ruleFrom.account"
                name="dy号"
                label="dy号"
                placeholder="dy号"
                :rules="[{ required: true, message: '请填写dy号' }]"
              />
              <van-field
                v-model="ruleFrom.amount"
              type="digit"
                name="充值金额"
                label="充值金额"
                placeholder="充值金额"
                :rules="[{ required: true, message: '请填写充值金额' }]"
              />
              <van-field
              v-model="ruleFrom.remark"
              rows="4"
              autosize
              label="备注"
              type="textarea"
              maxlength="150"
              placeholder="请输入备注"
              show-word-limit
            />
            </van-cell-group>
            <div style="margin: 16px;">
              <van-button round block type="primary" native-type="submit">
                提交
              </van-button>
            </div>
          </van-form>
        <van-dialog  closeable
        close-icon="close" v-model:show="showDialog" title="支付码" :show-confirm-button="false">
          <div class="dialog-content">
            <div id="qrcode" ref="qrcodeRef"></div>
            <div class="flex items-center justify-center my-[20px]">
            <van-button type="primary" @click="downloadQRCode" class="mt-4">下载二维码</van-button>

            </div>
          </div>
        </van-dialog>
    </div>
  </template>

  <script lang="ts" setup>
import { showToast ,closeToast, showLoadingToast} from 'vant';

  import api from '@/api/api'
  import qrcode from 'qrcodejs2-fix'
import { useAutoRequest } from '@/hooks/loading';
import { ref, nextTick } from 'vue'
import { Dialog } from 'vant'

  const [loading, CreateOrder] = useAutoRequest(api.CreateOrder)
  const ruleFrom =  ref({
    account: '',
    amount: '',
    remark: '',
  })

  const qrcodeRef = ref(null)
  const showDialog = ref(false)

   const onSubmit = async (values) => {
     const data=  await CreateOrder(ruleFrom.value)
     if (qrcodeRef.value) {
       qrcodeRef.value.innerHTML = ''
     }
    showDialog.value = true
     await nextTick()
     new qrcode(qrcodeRef.value, {
       text: data.url,
       width: 200,
       height: 200,
       colorDark: "#000000",
       colorLight: "#ffffff",
       correctLevel: qrcode.CorrectLevel.H
     })
    //  window.open(data.url)
    };

    const downloadQRCode = async () => {
  showLoadingToast({
    message: '保存中...',
    forbidClick: true,
  });

  const canvas = qrcodeRef.value?.querySelector('canvas');
  if (!canvas) {
    closeToast();
    showToast('获取二维码失败');
    return;
  }
    console.log(window.plus)
    const base64 = canvas.toDataURL('image/png');
    console.log(base64)

    const base64Data = base64.replace(/^data:image\/\w+;base64,/, '');
    saveImg('qr',base64Data, 10)
};
function saveImg(fileName, base64, quality) {
				quality = quality || 10
				const bitmap = new plus.nativeObj.Bitmap()
				// 从本地加载Bitmap图片
				bitmap.loadBase64Data(base64, function() {
					bitmap.save("_doc/" + fileName + ".jpg", {
						overwrite: true,
						quality: quality
					}, function(i) {
						// callback(i);
						// mui.alert("保存图片成功：" + JSON.stringify(i))
						savePicture(i.target)
					}, function(e) {
					})
				}, function(e) {
				})
			}
      function savePicture(file) {
				plus.gallery.save(file, function() {
						showToast("图片保存完成！")
				}, function(e) {
					if (e.code === -3310 || e.code === 8) {
						showToast("您已禁止访问相册,请设置开启权限")
					} else {
						showToast("图片保存失败:" + JSON.stringify(e))
					}
				})
			}
const router = useRouter()
const onClickLeft = ()=> {
  router.back()
}
  </script>
  <style scoped lang="scss">
  #qrcode {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  </style>

